<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix"><span>更换图片</span></div>
    <div>
      <img :src="url" alt="" v-if="url" style="height: 350px; width: 350; object-fit: cover" />
      <img src="@/assets/images/avatar.jpg" alt="" v-else />
    </div>
    <div class="box">
      <el-button type="primary" icon="el-icon-plus" @click="send">选择图片</el-button>
      <input type="file" ref="file" style="display: none" @change="filechange" />
      <el-button type="success" icon="el-icon-upload" :disabled="url ? false : true" @click="uploda"
        >上传图片</el-button
      >
    </div>
  </el-card>
</template>

<script>
import { uplodAPI } from '@/api/user'
export default {
  name: 'UserArat',
  data() {
    return {
      url: ''
    }
  },

  methods: {
    send() {
      this.$refs.file.click()
    },

    filechange(e) {
      if (e.target.files.length > 0) {
        const obj = e.target.files[0]
        const fr = new FileReader()
        fr.readAsDataURL(obj)
        fr.onload = () => {
          this.url = fr.result
        }
      } else {
        this.url = ''
      }
    },

    async uploda() {
      const { data: res } = await uplodAPI(this.url)
      // console.log(res)
      if (res.code === 0) {
        this.$message.success(res.message)
        this.$store.dispatch('user/getUser')
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>
<style scoped>
.box {
  margin-top: 10px;
}
.el-card {
  font-size: 13px;
}
</style>
